package com.itheima.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 阿里云 OSS 工具类
 */
@Data
public class AliOSSUtils {

    private AliOSSProperties aliOSSPro;

    /**
     * 实现上传图片到OSS
     * @param multipartFile 接收到的前端文件
     * @return url
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) + multipartFile.getOriginalFilename();

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(
                aliOSSPro.getEndpoint(),
                aliOSSPro.getAccessKeyId(),
                aliOSSPro.getAccessKeySecret());
        ossClient.putObject(aliOSSPro.getBucketName(), fileName, inputStream);

        //文件访问路径
        String url = aliOSSPro.getEndpoint().split("//")[0] + "//" + aliOSSPro.getBucketName() + "." + aliOSSPro.getEndpoint().split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
